package com.cykj.pos.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ayg.openapi.utils.ParameterUtils;
import com.ayg.openapi.utils.RsaUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cykj.common.config.RuoYiConfig;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.common.core.domain.model.LoginBody;
import com.cykj.common.utils.SecurityUtils;
import com.cykj.pos.controller.TestDTO.HttpClientHandler;
import com.cykj.pos.domain.*;
import com.cykj.pos.domain.dto.*;
import com.cykj.pos.domain.dto.BizServerFlowRate;
import com.cykj.pos.domain.dto.MerchVO;
import com.cykj.pos.domain.dto.MerchantVO;
import com.cykj.pos.domain.dto.PosMerchantRelatedDTO;
import com.cykj.pos.domain.dto.ayg.ApiBaseParam;
import com.cykj.pos.domain.dto.ayg.ApiBaseResult;
import com.cykj.pos.domain.vo.BizeServerCharge;
import com.cykj.pos.enums.bizstatus.BizStatusContantEnum;
import com.cykj.pos.mapper.BizMerchantEntryMapper;
import com.cykj.pos.mapper.BizPosMachineMapper;
import com.cykj.pos.payment.controller.CallbackController;
import com.cykj.pos.profit.dto.*;
import com.cykj.pos.service.*;
import com.cykj.pos.service.impl.BizMerchantReceiverServiceImpl;
import com.cykj.pos.test.TestPOJO;
import com.cykj.pos.util.*;
import com.cykj.system.service.ISysUserService;
import com.google.gson.Gson;
import com.sec.sdk.constants.SecGatewayConstants;
import com.sun.jna.platform.win32.OaIdl;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.aspectj.weaver.loadtime.Aj;
import org.json.JSONString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.security.PrivateKey;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;

@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/noauth")
@Api(tags = "注册")
public class PartnerOpenInterfaceController {
    private final IWxLicationService wxLicationService;

    private final IBizMerchantService merchantService;
    private final BizPosMachineMapper bizPosMachineMapper;

    private final IBizMerchantService iBizMerchantService;

    private final IBizVerifyCodeService iBizVerifyCodeService;

    private final IBizPosMachineService iBizPosMachineService;

    private final IDataSecurityService dataSecurityService;

    private final IBizVerifyCodeService verifyCodeService;

    private final ISysUserService sysUserService;

    private final IBizMerchantEntryService iBizMerchantEntryService;

    private final IBizVersionRecordService versionRecordService;
    private final BizPosMachineMapper posMachineMapper;

    private final BizMerchantReceiverServiceImpl bizMerchantReceiverService;

    private final IBizPosMachineStatusRecordsService machineStatusRecordsService;

    private final IBizWalletService walletService;

    private final IBizMerchTransactionsService BizMerchTransactionsService;

    private final RuoYiConfig config;

    private final IBizPosStorageService bizPosStorageService;

    private final IBizFeesChargedService bizFeesChargedService;

    private final IBizPosTypeService bizPosTypeService;

    private final IBizMerchantEntryService bizMerchantEntryService;

    private final IBizPosBrandService bizPosBrandService;
    @Resource
    private BizMerchantEntryMapper bizMerchantEntryMapper;

    // 显示版本信息接口
    @GetMapping("/getVersionInfo/{id}")
    public AjaxResult getNewsVersionInfo(@PathVariable String id) {
        AjaxResult ajaxResult = AjaxResult.success("获取版本信息成功");
//        BizVersionRecord versionRecord = versionRecordService.getNewsVersionInfo();
        BizVersionRecord versionRecord = versionRecordService.getNewsVersionInfoById(id);
        if (versionRecord == null) {
            return AjaxResult.error("当前系统没有上传任何版本信息");
        }
        ajaxResult.put("data", versionRecord);
        return ajaxResult;
    }

    @ApiOperation(value = "发送短信验证码")
    @ApiImplicitParams({@ApiImplicitParam(name = "mobile", value = "路径参数1：合法手机号码", dataType = "long", required = true, paramType = "body"),
            @ApiImplicitParam(name = "inviteCode", value = "邀请码，即邀请商户编码", dataType = "long", required = true, paramType = "body")})
    @ApiResponses({@ApiResponse(code = 200, response = AjaxResult.class, message = "业务数据响应成功")})
    @GetMapping("/verifyCode/sender/{mobile}/{inviteCode}")
    public AjaxResult verifyCodeSender(@PathVariable String mobile, @PathVariable String inviteCode) {

        LambdaQueryWrapper<BizMerchant> lqw = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(inviteCode)) {
            lqw.eq(BizMerchant::getMerchCode, inviteCode);
        }
        BizMerchant merchant = iBizMerchantService.getOne(lqw);

        if (merchant == null) {
            return AjaxResult.error(BizStatusContantEnum.BIZ_FAIL.getName());
        }
        BizStatusContantEnum bizStatus = iBizVerifyCodeService.sendVerifyCode(mobile, merchant.getUserId());
        if (bizStatus == BizStatusContantEnum.BIZ_SUCCESS) return AjaxResult.success("短信验证码发送成功");


        return AjaxResult.error(bizStatus.getName());
    }

    @ApiOperation("注册")
    @PostMapping("/partner/register")
    public AjaxResult partnerRegister(@RequestBody PartnerInviteDTO partnerInviteDTO) {
        String mobile = partnerInviteDTO.getMobile();
        String verifyCode = partnerInviteDTO.getVerifyCode();
        // 校验验证码 测试先注释掉
       /* BizStatusContantEnum bizStatus = iBizVerifyCodeService.verifyCodeValidate(mobile, verifyCode);
        if (bizStatus != BizStatusContantEnum.SMS_SUCCESS) {
            return AjaxResult.error(bizStatus.getName());
        }*/
        BizStatusContantEnum status = iBizMerchantService.partnerRegister(partnerInviteDTO);
        System.out.println("提现费率id"+partnerInviteDTO.getWithdrawalId());
        if (status != BizStatusContantEnum.PARTNER_REGISTER_SUCCESS) {
            return AjaxResult.error(status.getName());
        }
        return AjaxResult.success(BizStatusContantEnum.PARTNER_REGISTER_SUCCESS.getName());
    }

    @PostMapping("/merchant/transaction/append")
    public KuaiQianResult addMerchantTransaction(@RequestBody ThirdPartRequestDataDTO<String> requestDataDTO) {
        System.out.println("**************************************************************");
        System.out.println("-----" + DateUtils.dateFormatString(new Date()) + "-------------");
        System.out.println("------------------------------------------------------------");
        System.out.println("------------快钱接口调用新增商户消费交易记录接口---------------");
        System.out.println("------------------------------------------------------------");
        System.out.println("------------------------------------------------------------");
        System.out.println(requestDataDTO);
        System.out.println("------------------------------------------------------------");
        System.out.println("**************************************************************");
        String sign = requestDataDTO.getSign();
        String data = requestDataDTO.getData();
        /*boolean verify = dataSecurityService.dataVerfiy(sign,data);
        if(!verify)return new KuaiQianResult("01","验证失败");*/
        // 工具类型
        BizMerchTransDTO merchTransDTO = JSONObject.parseObject(data, BizMerchTransDTO.class);
        // 转换成数据转换对象
        iBizMerchantService.addMerchantTransaction(merchTransDTO);
        return new KuaiQianResult("00", "新增商户消费交易记录成功");
    }

    @PostMapping("/merchant/transaction/cancel")
    public KuaiQianResult cancelMerchantTransaction(@RequestBody ThirdPartRequestDataDTO<String> requestDataDTO) {
        System.out.println("**************************************************************");
        System.out.println("-----" + DateUtils.dateFormatString(new Date()) + "-------------");
        System.out.println("------------------------------------------------------------");
        System.out.println("------------快钱接口调用新增商户消费交易撤消接口------------------");
        System.out.println("------------------------------------------------------------");
        System.out.println("------------------------------------------------------------");
        System.out.println(requestDataDTO);
        System.out.println("------------------------------------------------------------");
        System.out.println("**************************************************************");
        String sign = requestDataDTO.getSign();
        String data = requestDataDTO.getData();
        System.out.println(sign);
        System.out.println(data);
        /*boolean verify = dataSecurityService.dataVerfiy(sign,data);
        if(!verify)return new KuaiQianResult("01","验证失败");*/
        // 转换成数据转换对象
        BizCancelTransDTO merchTransDTO = JSONObject.parseObject(data, BizCancelTransDTO.class);
        iBizMerchantService.cancelMerchantTransaction(merchTransDTO);
        return new KuaiQianResult("00", "商户消费交易记录撤消成功");
    }

    @PostMapping("/merchant/transaction/return")
    public KuaiQianResult returnMerchantTransaction(@RequestBody ThirdPartRequestDataDTO<String> requestDataDTO) {
        System.out.println("**************************************************************");
        System.out.println("-----" + DateUtils.dateFormatString(new Date()) + "-------------");
        System.out.println("------------------------------------------------------------");
        System.out.println("------------------------------------------------------------");
        System.out.println("------------快钱接口调用消费交易记录退货接口------------------");
        System.out.println("------------------------------------------------------------");
        System.out.println("------------------------------------------------------------");
        System.out.println(requestDataDTO);
        System.out.println("------------------------------------------------------------");
        System.out.println("**************************************************************");
        String sign = requestDataDTO.getSign();
        String data = requestDataDTO.getData();
       /* boolean verify = dataSecurityService.dataVerfiy(sign, data);
        if(!verify)return new KuaiQianResult("01","验证失败");*/
        // 转换成数据转换对象
        BizReturnTransDTO merchTransDTO = JSONObject.parseObject(data, BizReturnTransDTO.class);
        iBizMerchantService.returnMerchantTransaction(merchTransDTO);
        return new KuaiQianResult("00", "商户消费交易记录退货成功");
    }

    @PostMapping("/terminal/bind")
    public KuaiQianResult posMacineBind(@RequestBody ThirdPartRequestDataDTO<String> requestDataDTO) {
        System.out.println("**************************************************************");
        System.out.println("-----" + DateUtils.dateFormatString(new Date()) + "-------------");
        System.out.println("------------------------------------------------------------");
        System.out.println("------------------------------------------------------------");
        System.out.println("------------快钱接口调用设备绑定接口------------------");
        System.out.println("------------------------------------------------------------");
        System.out.println("------------------------------------------------------------");
        System.out.println(requestDataDTO);
        System.out.println("------------------------------------------------------------");
        System.out.println("**************************************************************");
        String sign = requestDataDTO.getSign();
        String data = requestDataDTO.getData();
        /*boolean verify = dataSecurityService.dataVerfiy(sign, data);
        if(!verify)return new KuaiQianResult("01","验证失败");*/
        // 转换成数据转换对象
        TerminalBindDTO terminalBindDTO = JSONObject.parseObject(data, TerminalBindDTO.class);
        KuaiQianResult result = iBizPosMachineService.posMachineBind(terminalBindDTO);
        return result;
    }

    @PostMapping("/terminal/activation")
    public KuaiQianResult posMacineActivate(@RequestBody ThirdPartRequestDataDTO<String> requestDataDTO) {
        System.out.println("**************************************************************");
        System.out.println("-----" + DateUtils.dateFormatString(new Date()) + "-------------");
        System.out.println("------------------------------------------------------------");
        System.out.println("------------------------------------------------------------");
        System.out.println("--------------------快钱接口调用设备激活接口------------------");
        System.out.println("------------------------------------------------------------");
        System.out.println("------------------------------------------------------------");
        System.out.println(requestDataDTO);
        System.out.println("------------------------------------------------------------");
        System.out.println("**************************************************************");
        System.out.println(requestDataDTO);
        String sign = requestDataDTO.getSign();
        String data = requestDataDTO.getData();
        /*boolean verify = dataSecurityService.dataVerfiy(sign, data);
        if(!verify)return new KuaiQianResult("01","验证失败");*/
        TerminalActivateDTO terminalActivateDTO = JSONObject.parseObject(data, TerminalActivateDTO.class);
        // 转换成数据转换对象
        KuaiQianResult result = iBizPosMachineService.posMachineActivate(terminalActivateDTO);
        return result;
    }

    @ApiOperation(value = "找回登录密码")
    @ApiImplicitParams({@ApiImplicitParam(name = "password", value = "登录密码密文", dataType = "string", required = true, paramType = "body")})
    @ApiResponses({@ApiResponse(code = 200, response = PartnerInviteDTO.class, message = "登录密码重置成功")})
    @PostMapping("/password/reset")
    public AjaxResult resetLoginPassword(@RequestBody PartnerInviteDTO partnerInviteDTO) {
        AjaxResult ajaxResult = AjaxResult.success("登录密码重置成功");
        String mobile = partnerInviteDTO.getMobile();
        String verifyCode = partnerInviteDTO.getVerifyCode();
        BizStatusContantEnum bizStatus = verifyCodeService.verifyCodeValidate(mobile, verifyCode);
        if (bizStatus != BizStatusContantEnum.SMS_SUCCESS) {
            return AjaxResult.error(bizStatus.getName());
        }
        //密码密文处理，前端算法解密-新算法加密-保存
        String password = SecurityUtils.encryptPassword(partnerInviteDTO.getPassword());
        sysUserService.resetUserPwd(mobile, password);
        return ajaxResult;
    }

    @ApiOperation(value = "APP用户发送短信验证码")
    @ApiImplicitParams({@ApiImplicitParam(name = "mobile", value = "路径参数1：合法手机号码", dataType = "long", required = true, paramType = "body")})
    @ApiResponses({@ApiResponse(code = 200, response = AjaxResult.class, message = "业务数据响应成功")})
    @GetMapping("/verifyCode/sender/{mobile}")
    public AjaxResult verifyCodeSender(@PathVariable String mobile) {
        SysUser sysUser = sysUserService.selectUserByUserName(mobile);
        if (sysUser == null) {
            return AjaxResult.error("用户非法");
        }
        BizStatusContantEnum bizStatus = iBizVerifyCodeService.sendVerifyCode(mobile, sysUser.getUserId());
        if (bizStatus == BizStatusContantEnum.BIZ_SUCCESS) return AjaxResult.success("短信验证码发送成功");
        return AjaxResult.error(bizStatus.getName());
    }

    // 更新设备信息
    @ApiOperation(value = "更改设备信息")
    @PostMapping("/updateMSRecords")
    public AjaxResult updateMachineStatusRecords(@RequestBody BizPosMachineStatusRecords biz) {
        // 通过sn_code来查询此信息
        String snCode = biz.getSnCode();
        if (biz.getPhoneNo() == null) {
            return AjaxResult.error("手机号不能为空");
        }
        if (biz.getSnCode() == null) {
            return AjaxResult.error("设备号不能为空");
        }
        if (biz.getName() == null) {
            return AjaxResult.error("姓名不能为空");
        }
        if (biz.getBankCardno() == null) {
            return AjaxResult.error("银行卡号不能为空");
        }
        if (biz.getBankType() == null) {
            return AjaxResult.error("所属银行不能为空");
        }
        BizPosMachineStatusRecords biz_records = merchantService.selectBizPosMachineStatusRecords(snCode);
        if (biz_records == null) {
            return AjaxResult.error("未查到此设备信息");
        }
        // 有信息
        // 判断是否已绑定
        String status = biz_records.getStatus();
        if (status.equals("2")) {
            return AjaxResult.error("该设备已经绑定");
        }
        // 再先判断是否被激活
        String recordsType = biz_records.getRecordsType();
        if (recordsType.equals("1")) {
            return AjaxResult.error("此设备未激活");
        }
        // 判断身份证 手机号后四位
        // 截取手机号后四位
        if (biz_records.getPhoneNo().equals("") || biz_records.getName().equals("")) {
            // 单独判段手机号或者姓名
            if (!biz_records.getPhoneNo().equals("")) {
                // 手机号不为空 判断手机号时候相同
                String phone = biz.getPhoneNo().substring(biz.getPhoneNo().length() - 4);
                String phone1 = biz_records.getPhoneNo().substring(biz_records.getPhoneNo().length() - 4);
                if (!phone.equals(phone1)) {
                    return AjaxResult.error("手机号不匹配");
                }
                machineStatusRecordsService.updateMachineStatusRecords(biz);
            }
            if (!biz_records.getName().equals("")) {
                String name = biz.getName();
                String name1 = biz_records.getName();
                if (!name.equals(name1)) {
                    return AjaxResult.error("名字不匹配");
                }
                machineStatusRecordsService.updateMachineStatusRecords(biz);
            }
            // 更新数据
            machineStatusRecordsService.updateMachineStatusRecords(biz);
            return AjaxResult.success("绑定成功");
        }
        // 前端传入手机号
        String phone = biz.getPhoneNo().substring(biz.getPhoneNo().length() - 4);
        // 查出的手机号
        String phone1 = biz_records.getPhoneNo().substring(biz_records.getPhoneNo().length() - 4);
        // 传入的姓名
        String name = biz.getName();
        // 查出的姓名
        String name1 = biz_records.getName();
        if (phone.equals(phone1) && name.equals(name1)) {
            // 更新数据
            machineStatusRecordsService.updateMachineStatusRecords(biz);
            return AjaxResult.success("绑定成功");
        }
        if (!phone.equals(phone1)) {
            return AjaxResult.error("手机号不匹配");
        }
        return AjaxResult.error("名字不匹配");
    }


    // 获取微信公众号签名
    @ApiOperation(value = "获取微信公众号签名")
    @PostMapping("/wxLicationInfo")
    public AjaxResult queryWxLicationInfo(@RequestBody WxLication wxLication1) {
        // 获取微信应用信息
        int id = 1;
        WxLication wxLication = wxLicationService.queryWxLicationInfo(id);
        // 返回结果对象
        ResultWxLication resultWxLication = new ResultWxLication();
        Date currentTime = new Date();
        String url = null;
        try {
            url = URLDecoder.decode(wxLication1.getUrl(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        wxLication.setUrl(url);
        // 先判断超没超时 超时重新生成签名
        if (currentTime.getTime() - wxLication.getTicketTime().getTime() > 3600000L) {
            WxLication newWxLication = GetJsapiTicket.signature(wxLication);
            newWxLication.setId(1L);
            // 把这些信息存入数据库
            wxLicationService.saveWxLicationInfo(newWxLication);
            resultWxLication.setAppId(newWxLication.getAppId());
            resultWxLication.setNonceStr(newWxLication.getNonceStr());
            resultWxLication.setTimestamp(newWxLication.getTimestamp());
            resultWxLication.setSignature(newWxLication.getSignature());
            return AjaxResult.success("微信公众号", resultWxLication);
        }
        // 没有超时 不用重新获得签名
        //3、时间戳和随机字符串
        String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳
        //4、获取url
        String newurl = url;
        //5、将参数排序并拼接字符串
        String str = "jsapi_ticket=" + wxLication.getJsapiTicket() + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + newurl;
        //6、将字符串进行sha1加密
        String signature = GetJsapiTicket.SHA1(str);
        resultWxLication.setAppId(wxLication.getAppId());
        resultWxLication.setNonceStr(noncestr);
        resultWxLication.setTimestamp(timestamp);
        resultWxLication.setSignature(signature);
        return AjaxResult.success("微信公众号", resultWxLication);
    }

    private Logger logger = LoggerFactory.getLogger(CallbackController.class);

    // 支付成功回调
    @ApiOperation(value = "支付接口回调")
    @PostMapping("/payment/callBack")
    public String paymentCallBack(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        params.put(SecGatewayConstants.METHOD, request.getParameter(SecGatewayConstants.METHOD));
        params.put(SecGatewayConstants.SIGN_TYPE, request.getParameter(SecGatewayConstants.SIGN_TYPE));
        params.put(SecGatewayConstants.SIGN, request.getParameter(SecGatewayConstants.SIGN));
        params.put(SecGatewayConstants.TIMESTAMP, request.getParameter(SecGatewayConstants.TIMESTAMP));
        params.put(SecGatewayConstants.VERSION, request.getParameter(SecGatewayConstants.VERSION));
        params.put(SecGatewayConstants.MERCHANT_REQUEST_NO, request.getParameter(SecGatewayConstants.MERCHANT_REQUEST_NO));
        params.put(SecGatewayConstants.BIZ_CONTENT_KEY, request.getParameter(SecGatewayConstants.BIZ_CONTENT_KEY));
        String bizContent = request.getParameter(SecGatewayConstants.BIZ_CONTENT_KEY);
        String result = walletService.paymentCallBack(params, bizContent);
        return result;
    }

    // 易支付回调
    @ApiOperation(value = "易支付接口回调")
    @RequestMapping("/ayg/deliverapi_callback")
    public ApiBaseResult payCallBack(HttpServletRequest request, @RequestBody ApiBaseParam param) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = df.format(new Date());
        System.out.println("-------------------------------" + strDate + "---------------------------------------");
        System.out.println("------------------------------***易支付接口回调支付接口回调***----------------------------");
        System.out.println("-------------------------------------------------------------------------------------");
        System.out.println("进入回调服务.");
        ApiBaseResult apiBaseResult = walletService.deliverapiCallback(param);
        return apiBaseResult;
    }

    // 主动查询订单
    @RequestMapping("/ayg/queryPayOrder")
    public AjaxResult queryPayOrder() {
        AjaxResult ajaxResult = AjaxResult.success("易支付主动查询接口查询成功");
        String url = "https://openapi.opensaas.net.cn/deliver/dlvopenapi/api/app/pay/query";
        Map<String, Object> params = new Hashtable<>();
        params.put("appId", "210517019961739059");
        params.put("method", "ayg.salary.payQuery");
        params.put("version", "1.0");
        params.put("nonce", "" + System.currentTimeMillis() + new Random().nextInt(1000));
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = df.format(new Date());
        params.put("timestamp", strDate);
        params.put("signType", "RSA2");
        Map<String, String> data = new Hashtable<>();
        data.put("reqNo", "31c5629c0eb74d1aa29ba677ab5e688e");  // 下单时生成的请求流水号
        data.put("outOrderNo", "100011622448087534"); // 企业系统内部订单号
        params.put("data", data);
        String signatureContent = ParameterUtils.mapToSignContent(params);
        PrivateKey appPrivateKey = RsaUtils.loadPrivateKey(config.getAppRsaPrivatekey());
        String sign = RsaUtils.signature(appPrivateKey, signatureContent);// 生成签名字符串
        params.put("sign", sign);
        System.out.println(params);
        String str = HttpUtils.httpPostJson(url, params);
        System.out.println(str);
        return ajaxResult;
    }

    @ApiOperation(value = "测试接口")
    @PostMapping("/pos/merchant/related")
    public AjaxResult test(@RequestBody PosMerchantRelatedDTO posMerchantRelatedDTO) {
        AjaxResult ajaxResult = AjaxResult.success("商户团队和pos机器绑定成功");
        machineStatusRecordsService.generatePosMerchantRelatedProcedure(posMerchantRelatedDTO.getPosCode(), posMerchantRelatedDTO.getMerchId());
        ajaxResult.put("data", "success");
        return ajaxResult;
    }

    // 激活达标显示登陆
    @ApiOperation(value = "激活达标登陆")
    @PostMapping("/pos/activate/login")
    public AjaxResult activateLogin(@RequestBody BizPosMachineStatusRecords bizPosMachineStatusRecords) {
        AjaxResult ajaxResult = AjaxResult.success("激活达标");
        ActivateMerchDTO activateMerchDTO = new ActivateMerchDTO();
        if (bizPosMachineStatusRecords == null) {
            return AjaxResult.error("请输入设备号或电话号");
        }
        BizPosMachineStatusRecords posInfo = machineStatusRecordsService.queryPosInfoBySncodeOrPhone(bizPosMachineStatusRecords);
        List<ActivateReachDTO> list = null;
        if (posInfo == null) {// 说明没有改设备
            return AjaxResult.error("没有该设备信息");
        } else if (posInfo.getRecordsType().equals("1")) {
            return AjaxResult.error("该设备没有激活");
        } else {
            // 按月查询激活设备交易量
            list = BizMerchTransactionsService.queryActivatePosMonthAmount(posInfo);
            activateMerchDTO.setName(posInfo.getName());
            StringBuilder sb = new StringBuilder(posInfo.getPhoneNo());
            sb.replace(3, 7, "****");// 数组替换
            activateMerchDTO.setPhone("手机号：" + sb);
            activateMerchDTO.setSnCode("SN码：" + posInfo.getSnCode());
            activateMerchDTO.setActivateTime("激活时间：" + posInfo.getActiveTime());
        }
        BigDecimal bigDecimal = new BigDecimal("10000");
        for (ActivateReachDTO activateReachDTO : list) {
            if (activateReachDTO.getMonthAmount().compareTo(bigDecimal) == 0 || activateReachDTO.getMonthAmount().compareTo(bigDecimal) == 1) {
                // 小于10000
                activateReachDTO.setPercentage("100%");
            } else if (activateReachDTO.getMonthAmount().compareTo(bigDecimal) == -1) {
                BigDecimal bigDecimal1 = new BigDecimal("100");
                BigDecimal a = activateReachDTO.getMonthAmount().divide(bigDecimal);
                BigDecimal b = a.multiply(bigDecimal1);
                String c = b.toString();
                String d = c.substring(0, 2) + "%";
                activateReachDTO.setPercentage(d);
            }
        }
        if (list.size() > 0) {
            if (list.get(list.size() - 1).getReach() == 1) {// 未达标 但是时间未到 显示进行中
                list.get(list.size() - 1).setReach(2);
            }
        }
        // 进行中
        // Collections.reverse(list);// 逆排序
        ajaxResult.put("data", list);
        ajaxResult.put("activate", activateMerchDTO);
        return ajaxResult;
    }

    @GetMapping("/test")
    public AjaxResult test(HttpServletResponse response) throws Exception {
        AjaxResult ajaxResult = AjaxResult.success("生成团队上下级关系");
        BizMerchant bizMerchant = new BizMerchant();
        // 查出所有的商户
        List<BizMerchant> list = merchantService.queryList(bizMerchant);
        List<TestPOJO> list1 = new ArrayList<TestPOJO>();
        for (int i = 0; i < list.size(); i++) {
            // 通过这个人merch_id 去查他的上级
            TestPOJO testPOJO = merchantService.queryAllParent(list.get(i));
            list1.add(i, testPOJO);
        }
        ajaxResult.put("data", list1);
        ExcelData data = new ExcelData();
        data.setName("hello");// sheet表名称
        List<String> titles = new ArrayList();
        titles.add("伙伴名称");
        titles.add("上下级关系");
        data.setTitles(titles);
        List<List<Object>> rows = new ArrayList();
        int a = 0;
        for (int i = 0; i < list1.size(); i++) {
            List<Object> row1 = new ArrayList();
            if (list1.get(i).getParentName() == null) {
                continue;
            }
            if (list1.get(i).getParentName() != null) {
                row1.add(list1.get(i).getMySelf());
                row1.add(list1.get(i).getParentName());
                rows.add(a, row1);
                a++;
            }
        }
        data.setRows(rows);
        ExportExcelUtils.exportExcel(response, "分润.xlsx", data);
        return ajaxResult;
    }

    @PostMapping("/terminal/sftApi")
    public String posMacineBindNew(ShengFuTongTradeDTO shengFuTongTradeDTO) throws Exception {
//        System.out.println("*************************"+shengFuTongTradeDTO+"*************************************");
//        System.out.println("-----"+DateUtils.dateFormatString(new Date())+"-------------");
//        System.out.println("------------------------------------------------------------");
//        System.out.println("------------------------------------------------------------");
//        System.out.println("----------盛付通接口调用设备绑定,激活，交易通知通用接口--------");
//        System.out.println("------------------------------------------------------------");
//        System.out.println("------------------------------------------------------------");
//        System.out.println("------------------------------------------------------------");
//        System.out.println("**************************************************************");
//        String jsonExtData = shengFuTongTradeDTO.getDataJson();
//        ShengFuTongTradeDTO shengFuTong = new Gson().fromJson(jsonExtData,ShengFuTongTradeDTO.class);
        if (shengFuTongTradeDTO.getExtData() != null) {
            System.out.println("*************************" + shengFuTongTradeDTO + "*************************************");
            System.out.println("-----" + DateUtils.dateFormatString(new Date()) + "-------------");
            System.out.println("------------------------------------------------------------");
            System.out.println("------------------------------------------------------------");
            System.out.println("----------盛付通交易通知通用接口--------");
            System.out.println("------------------------------------------------------------");
            System.out.println("------------------------------------------------------------");
            System.out.println("------------------------------------------------------------");
            boolean b = iBizMerchantService.addMerchantTransactionBySft(shengFuTongTradeDTO);//盛付通交易记录
            if (b) {
                return ("SUCCESS");
            }
            return ("false");
        } else if (shengFuTongTradeDTO.getBusinessType().equals("1")) {
            System.out.println("*************************" + shengFuTongTradeDTO + "*************************************");
            System.out.println("-----" + DateUtils.dateFormatString(new Date()) + "-------------");
            System.out.println("------------------------------------------------------------");
            System.out.println("------------------------------------------------------------");
            System.out.println("----------盛付通接口调用设备绑定接口--------");
            System.out.println("------------------------------------------------------------");
            System.out.println("------------------------------------------------------------");
            System.out.println("------------------------------------------------------------");
            boolean b = iBizPosMachineService.posMachineSftBind(shengFuTongTradeDTO);//盛付通绑定
            if (b) {
                return ("SUCCESS");
            }
            return ("false");

        } else if (shengFuTongTradeDTO.getBusinessType().equals("2")) {
            System.out.println("*************************" + shengFuTongTradeDTO + "*************************************");
            System.out.println("-----" + DateUtils.dateFormatString(new Date()) + "-------------");
            System.out.println("------------------------------------------------------------");
            System.out.println("------------------------------------------------------------");
            System.out.println("----------盛付通接口调用激活接口--------");
            System.out.println("------------------------------------------------------------");
            System.out.println("------------------------------------------------------------");
            System.out.println("------------------------------------------------------------");
            int i = iBizPosMachineService.posMachineSftActiv(shengFuTongTradeDTO);//盛付通激活
            if (i == 1) {
                return ("SUCCESS");
            }
            return ("false");
        } else if (shengFuTongTradeDTO.getBusinessType().equals("4")) {
            System.out.println("*************************" + shengFuTongTradeDTO + "*************************************");
            System.out.println("-----" + DateUtils.dateFormatString(new Date()) + "-------------");
            System.out.println("------------------------------------------------------------");
            System.out.println("------------------------------------------------------------");
            System.out.println("----------盛付通接口调用“”“结算”“”接口--------");
            System.out.println("------------------------------------------------------------");
            System.out.println("------------------------------------------------------------");
            System.out.println("------------------------------------------------------------");
            int i = iBizPosMachineService.posMachineSftSettle(shengFuTongTradeDTO);
            if (i == 1) {
                return ("SUCCESS");
            }
            return ("false");
        } else if (shengFuTongTradeDTO.getBusinessType().equals("5")) {
            System.out.println("*************************" + shengFuTongTradeDTO + "*************************************");
            System.out.println("-----" + DateUtils.dateFormatString(new Date()) + "-------------");
            System.out.println("------------------------------------------------------------");
            System.out.println("------------------------------------------------------------");
            System.out.println("----------盛付通接口调用“”“提现”“”接口--------");
            System.out.println("------------------------------------------------------------");
            System.out.println("------------------------------------------------------------");
            System.out.println("------------------------------------------------------------");
            int i = iBizPosMachineService.posMachineSftDeposit(shengFuTongTradeDTO);
            if (i == 1) {
                return ("SUCCESS");
            }
            return ("false");
        }

        return ("FAIL");
    }

    @PostMapping("/hello")
    public AjaxResult hello() {
        AjaxResult ajaxResult = new AjaxResult();
        List<BizWallet> list = walletService.queryAllWallet();
        List<Test> list1 = new ArrayList<Test>();
        for (int i = 0; i < list.size(); i++) {
            String key = list.get(i).getSecretKey();
            String p = list.get(i).getProfitAmount();
            String r = list.get(i).getRewardAmount();
            String z = list.get(i).getWalletAmount();
            String ps = DESHelperUtil.decrypt(key, p);
            String rs = DESHelperUtil.decrypt(key, r);
            String zs = DESHelperUtil.decrypt(key, z);
            BigDecimal bps = new BigDecimal(ps);
            BigDecimal brs = new BigDecimal(rs);
            BigDecimal bzs = new BigDecimal(zs);
            Test t = new Test();
            t.setId(list.get(i).getUserId());
            t.setP(bps);
            t.setR(brs);
            t.setZ(bzs);
            list1.add(i, t);
        }
        BigDecimal a = new BigDecimal("0");
        BigDecimal b = new BigDecimal("0");
        BigDecimal c = new BigDecimal("0");
        for (int i = 0; i < list1.size(); i++) {
            a = a.add(list1.get(i).getP());
            b = b.add(list1.get(i).getR());
            c = c.add(list1.get(i).getZ());

        }
        Test t = new Test();
        t.setP(a);
        t.setR(b);
        t.setZ(c);
        ajaxResult.put("data", t);
        return ajaxResult;
    }

    /**
     * 信息查询系统
     */
    @PostMapping("/query/info")
    public String queryInfo(@RequestBody PosInfoDTO posInfoDTO) {
        Map map = new HashMap<>();
        map.put("current", "1");
        map.put("method", "app.posm.mcccode.getList");
        map.put("no", "22");
        map.put("pageSize", "10");
        String url = "https://posm.posqz.com/mobile/api";
        String param = JSON.toJSONString(map);
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("contentType", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/json");
            // 发POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            //
            out.print(param);
            System.out.println(param + "##################################");
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响�?
            InputStream in1 = (conn.getInputStream());
            //解压input流内容
            GZIPInputStream gzip = new GZIPInputStream(in1);
            InputStreamReader inn = new InputStreamReader(gzip, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inn);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送请求失败：" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        try {
            System.out.println(new String(result.getBytes(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "00";
    }

    /**
     * 设备入库
     *
     * @return
     */
    @PostMapping("/storage")
    public AjaxResult posStorage() throws Exception {
        AjaxResult ajaxResult = AjaxResult.success("设备入库");
        List<BizPosStorage> posList = bizPosStorageService.list();// 查询所有设备
        List<BizPosType> posTypes = bizPosTypeService.list();// 设备类型
        for (BizPosStorage posStorage : posList) {
            // 设备表存信息
            // 已经绑定的存 激活表 激活状态2
            // 设备报件表存入信息
            BizPosMachineStatusRecords records = new BizPosMachineStatusRecords();
            BizPosMachine pos = new BizPosMachine();
            BizMerchantEntry entry = new BizMerchantEntry();// 报件信息
            if (null != posStorage.getMerchantNo()) {
                records.setMerchantId(posStorage.getMerchantNo());//商户编号
                entry.setMerchantNo(posStorage.getMerchantNo());
            }
            if (null != posStorage.getSnCode()) {
                pos.setPosCode(posStorage.getSnCode());// 设备号
                records.setSnCode(posStorage.getSnCode());
                entry.setSn(posStorage.getSnCode());
            }
            if (null != posStorage.getPosType()) {
                pos.setPosName(posStorage.getPosType());// 设备名
            }
            if (null != posStorage.getPosType()) {
                // 判断设备类型
                for (BizPosType posType : posTypes) {
                    if (posType.getTypeName().equals(posStorage.getPosType())) {
                        pos.setPosType(posType.getId().toString());// 设备类型号
                    }
                }
            }
            if (null != posStorage.getBindingType()) {
                if (posStorage.getBindingType().equals("已绑定")) {
                    pos.setPosActivateStatus("2");// pos已经激活
                    // 设备已经激活了 存一下激活表
                    records.setRecordsType("2");// 已经激活
                    records.setStatus("1");
                }
                if (posStorage.getBindingType().equals("未绑定")) {
                    pos.setPosActivateStatus("0");
                    records.setRecordsType("1");// 未激活
                    records.setStatus("1");
                }
            }
            if (null != posStorage.getBindingTime()) {// 时间
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                pos.setCreateTime(formatter.parse(DateUtils.dateConvertion(posStorage.getBindingTime())));
                pos.setPosBindTime(formatter.parse(DateUtils.dateConvertion(posStorage.getBindingTime())));
                records.setActiveTime(DateUtils.dateConvertion(posStorage.getBindingTime()));
                records.setTime(DateUtils.dateConvertion(posStorage.getBindingTime()));
                records.setReceiptDate(DateUtils.dateConvertion(posStorage.getBindingTime()));
            }
            if (null != posStorage.getBooksAre()) {// 入账人
                records.setName(posStorage.getBooksAre());
                entry.setApplicant(posStorage.getBooksAre());
            }
            if (null != posStorage.getPhoneNumber()) {
                entry.setAccountId(posStorage.getPhoneNumber());
            }
            pos.setMerchId(2L);// 服务中心下边
            iBizPosMachineService.save(pos);// 存入设备
            machineStatusRecordsService.save(records);
            if (null != posStorage.getBindingType()) {
                if (posStorage.getBindingType().equals("已绑定")) {
                    entry.setIsAudit("1");// 是否审核
                    bizMerchantEntryService.save(entry);// 未绑定的不存
                }
            }
        }
        return ajaxResult;
    }

    @PostMapping("/change")
    public AjaxResult change() {
        AjaxResult ajaxResult = AjaxResult.success("补全merchNo");
        List<BizPosMachine> list = iBizPosMachineService.list();
        for (BizPosMachine bizPosMachine : list) {
            String type = bizPosMachine.getPosType();
            LambdaQueryWrapper<BizPosType> le = Wrappers.lambdaQuery();
            le.eq(BizPosType::getId, type);
            BizPosType bizPosType = bizPosTypeService.getOne(le);
            bizPosMachine.setVar1(bizPosType.getBrandId().toString());
            iBizPosMachineService.saveOrUpdate(bizPosMachine);
        }
        return ajaxResult;
    }


    @PostMapping("/changetoo")
    public AjaxResult changetoo() {
        AjaxResult ajaxResult = AjaxResult.success("补全merchNo");
        List<BizPosMachine> list = iBizPosMachineService.list();
        List<BizPosType> types = bizPosTypeService.list();
        for (BizPosMachine bizPosMachine : list) {
            String name = bizPosMachine.getPosName();
            for (BizPosType bizPosType : types) {
                if (bizPosType.getTypeName().equals(name)) {
                    bizPosMachine.setVar1(bizPosType.getBrandId().toString());
                    bizPosMachine.setPosType(bizPosType.getId().toString());
                }
            }
            iBizPosMachineService.saveOrUpdate(bizPosMachine);
        }
        return ajaxResult;
    }

    @PostMapping("/getVar")
    public AjaxResult getVar() {
        return AjaxResult.success("获取成功", iBizPosMachineService.getVar());
    }

    /**
     * 商户解绑xxl
     *
     * @param
     */
    @PostMapping("/unbind")
    @Transactional
    public AjaxResult unbind(@RequestBody BizMerchantEntry bizMerchantEntry) throws Exception {
        AjaxResult ajaxResult = AjaxResult.success();
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        /*//查询商户入件
        BizMerchantEntry bizMerchantEntry = bizMerchantEntryService.getBizMerchantEntryBySn(snCode);*/
        String OUTMER = "OUTMER";
        String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=terminalinfoDao&Methods=update";
        Map<String, String> data = new HashMap<String, String>();
        data.put("merchant_no", bizMerchantEntry.getMerchantNo());
        data.put("sn", bizMerchantEntry.getSn());
        data.put("mersource", OUTMER);
        data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        data.put("key", bizAgentidAppkeyDTO.getKey());
        data.put("sign", PosOneUtil.generateSignature(data));
        System.out.println("----------" + PosOneUtil.generateSignature(data));
        System.out.println("---------" + data);
        String result = HttpClientHandler.noPictureRequest(url, data);
        System.out.println("返回:" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String retCode = jsonObject.getString("ret_code");
        String ret_msge = jsonObject.getString("ret_msge");
        if (retCode.equals("0")) { // 直接解绑成功了
            relieve(bizMerchantEntry.getSn());
        }
        if (retCode.equals("8")) {  //获取验证码
            String acqMobile = jsonObject.getString("acq_mobile");
            ajaxResult.put("acq_mobile", acqMobile);
        }
        ajaxResult.put("ret_msge", ret_msge);
        ajaxResult.put("retCode", retCode);
        return ajaxResult;
    }
    @PostMapping("/unbindByMerchantNos")
    public AjaxResult unbindByMerchantNos(String merchantNos){
        List<String> merchantNo=bizMerchantEntryMapper.selectAllMerantNo();
//        String [] merchantNo =merchantNos.split(";");
        for (String merchant:merchantNo){
            BizMerchantEntry bizMerchantEntry=bizMerchantEntryMapper.selectBizMerchantEntryMerchantNo(merchant);
            if(bizMerchantEntry==null||StringUtils.isBlank(bizMerchantEntry.getSn())){
                System.out.println(merchant+"\t找不到代理");
                continue;
            }
            try{
                AjaxResult result=this.unbindNew(bizMerchantEntry);
                System.out.println(bizMerchantEntry.getSn()+"\t"+bizMerchantEntry.getMerchantNo()+"\t"+result.get("ret_msge"));
            } catch (Exception e) {
            }

        }
        return AjaxResult.success();
    }

    @GetMapping("/unbindByMerchId")
    public AjaxResult unbindByMerchId(String merchIds){
        String [] merchIdsArr =merchIds.split(";");
        for (String merchId:merchIdsArr){
            String [] merchArr=merchId.split(",");
            String msg=merchId;
            merchId=bizMerchantEntryMapper.selectMerchIdByPhone(merchId);
            List<BizMerchantEntry> bizMerchantEntryList=new ArrayList<BizMerchantEntry>();
            if(merchArr.length>1){
                bizMerchantEntryList=bizMerchantEntryMapper.selectListByMechId(merchId);
            }else{
                bizMerchantEntryList=bizMerchantEntryMapper.selectListAllByMechId(merchId);
            }
            for(BizMerchantEntry bizMerchantEntry:bizMerchantEntryList){
                try {
                    AjaxResult result=this.unbindNew(bizMerchantEntry);
                    System.out.println(msg+"\t"+bizMerchantEntry.getSn()+"\t"+bizMerchantEntry.getMerchantNo()+"\t"+result.get("msg"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return AjaxResult.success();
    }


    public AjaxResult unbindNew(@RequestBody BizMerchantEntry bizMerchantEntry) throws Exception {
        AjaxResult ajaxResult = AjaxResult.success();
        Long userId=bizMerchantEntryMapper.selectUserId(bizMerchantEntry.getMerchId());
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(userId);
        /*//查询商户入件
        BizMerchantEntry bizMerchantEntry = bizMerchantEntryService.getBizMerchantEntryBySn(snCode);*/
        String OUTMER = "OUTMER";
        String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=terminalinfoDao&Methods=update";
        Map<String, String> data = new HashMap<String, String>();
        data.put("merchant_no", bizMerchantEntry.getMerchantNo());
        data.put("sn", bizMerchantEntry.getSn());
        data.put("mersource", OUTMER);
        data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        data.put("key", bizAgentidAppkeyDTO.getKey());
        data.put("sign", PosOneUtil.generateSignature(data));
        System.out.println("----------" + PosOneUtil.generateSignature(data));
        System.out.println("---------" + data);
        String result = HttpClientHandler.noPictureRequest(url, data);
        System.out.println("返回:" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String retCode = jsonObject.getString("ret_code");
        String ret_msge = jsonObject.getString("ret_msge");
        if (retCode.equals("0")) { // 直接解绑成功了
            relieve(bizMerchantEntry.getSn());
        }
        if (retCode.equals("8")) {  //获取验证码
            String acqMobile = jsonObject.getString("acq_mobile");
            ajaxResult.put("acq_mobile", acqMobile);
        }
        ajaxResult.put("ret_msge", ret_msge);
        ajaxResult.put("retCode", retCode);
        return ajaxResult;
    }

    /**
     * 商户解绑zhj    不连线上接口
     *
     * @param
     */
    @PostMapping("/unbindOld")
    @Transactional
    public AjaxResult unbindOld(@RequestBody BizMerchantEntry bizMerchantEntry) throws Exception {
        AjaxResult ajaxResult = AjaxResult.success();
        String fictitiousSnCode = "";
        //获取merchId merchName
        BizMerchant bizMerchant = iBizMerchantService.selectBizMerchantBySN(bizMerchantEntry.getSn());
        //生成虚拟sn
        fictitiousSnCode = IdWorker.getIdStr();
        //把虚拟sn存入设备表
        iBizPosMachineService.insertPosMachine(fictitiousSnCode, bizMerchant.getMerchId());
        //获取该sn所有交易记录
        List<BizMerchTransactions> list = BizMerchTransactionsService.selectBizMerchTransactions(bizMerchantEntry.getSn());
        if (list.size() > 0) {
            //把所有交易记录存入到解绑交易记录表
            BizMerchTransactionsService.insertbizMerchTransactionsUnbund(list, bizMerchant.getMerchId(), bizMerchant.getMerchName());
            //交易记录sn换成虚拟sn
            BizMerchTransactionsService.updateBizMerchTransactionsBySN(bizMerchantEntry.getSn(), fictitiousSnCode);
        }
        //获取激活信息  存解绑记录
        BizPosMachineStatusRecords bizPosMachineStatusRecords = machineStatusRecordsService.selectBizPosMachineStatusRecordsBysnCode(bizMerchantEntry.getSn());
        machineStatusRecordsService.insertBizPosRecordsNew(bizPosMachineStatusRecords);
        //删除激活表该sn数据
        machineStatusRecordsService.deleteBizPosRecordsNew(bizMerchantEntry.getSn());
        //删除报件 设备
        machineStatusRecordsService.deletebizentrySn( bizMerchantEntry.getSn());
        //设备状态改为0
        iBizMerchantService.updataMerchantStatus(bizMerchantEntry.getSn());
        //运行函数
        iBizMerchantService.generateAllPosMerchantRelatedProcedure();
        return ajaxResult;
    }

    @ApiOperation("商户解绑发送验证码")
    @PostMapping("/sendVerifyCode")
    public AjaxResult sendVerifyCode(String id) throws Exception {
        AjaxResult ajaxResult = AjaxResult.success();
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        String OUTMER = "OUTMER";
        String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=terminalinfounDao&Methods=add";
        Map<String, String> data = new HashMap<String, String>();
        data.put("acq_mobile", iBizPosMachineService.selectMerchantEntryPhone(Long.valueOf(id)));
        data.put("mersource", OUTMER);
        data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        data.put("key", bizAgentidAppkeyDTO.getKey());
        data.put("sign", PosOneUtil.generateSignature(data));
        System.out.println("----------" + PosOneUtil.generateSignature(data));
        System.out.println("---------" + data);
        String result = HttpClientHandler.noPictureRequest(url, data);
        System.out.println("返回:" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String ret_code = jsonObject.getString("ret_code");
        String ret_msge = jsonObject.getString("ret_msge");
        if (ret_code.equals("0")) { //发送验证码成功
            ajaxResult.put("ret_msge", ret_msge);
            ajaxResult.put("ret_code",ret_code);
            return ajaxResult;
        } else {
            ajaxResult.put("ret_msge", ret_msge);
            ajaxResult.put("ret_code",ret_code);
            return ajaxResult;
        }
    }

    @ApiOperation("商户解绑输入验证码")
    @PostMapping("/unBundle")
    public AjaxResult unBundle(@RequestBody BizUnBind bizUnBind) throws Exception {
        AjaxResult ajaxResult = AjaxResult.success();
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        String snCode = bizUnBind.getSnCode();
        BizMerchantEntry bizMerchantEntry = bizMerchantEntryService.getBizMerchantEntryBySn(bizUnBind.getSnCode());
        String OUTMER = "OUTMER";
        String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=terminalinfounDao&Methods=update";
        Map<String, String> data = new HashMap<String, String>();
        data.put("merchant_no", bizMerchantEntry.getMerchantNo());
        data.put("sn", bizUnBind.getSnCode());
        data.put("acq_mobile", iBizPosMachineService.selectMerchantEntryPhone(Long.valueOf(bizUnBind.getId())));
        data.put("verify_code", bizUnBind.getVerifyCode());
        data.put("mersource", OUTMER);
        data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        data.put("key", bizAgentidAppkeyDTO.getKey());
        data.put("sign", PosOneUtil.generateSignature(data));
        System.out.println("----------" + PosOneUtil.generateSignature(data));
        System.out.println("---------" + data);
        String result = HttpClientHandler.noPictureRequest(url, data);
        System.out.println("返回:" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String ret_code = jsonObject.getString("ret_code");
        String ret_msge = jsonObject.getString("ret_msge");
        if (ret_code.equals("0")) { //代表成功 执行咱们的逻辑
            relieve(snCode);
            System.out.println("------------------------");
            System.out.println("------------------------");
            System.out.println("已 经 解 绑 了  哈哈哈哈哈哈哈哈");
            System.out.println("------------------------");
            System.out.println("------------------------");
            ajaxResult.put("ret_msge", ret_msge);
            return ajaxResult;
        } else {
            ajaxResult.put("ret_msge", ret_msge);
            System.out.println("失败了" + ret_msge);
            return ajaxResult;
        }
    }

    /**
     * 商户绑定xxl
     *
     * @param merchantBindingTerminalDTO
     * @return
     */
    @PostMapping("/bound")
    @Transactional
    public AjaxResult bound(@RequestBody MerchantBindingTerminalDTO merchantBindingTerminalDTO) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        Date date=new Date();
        //查保健表  获取merchno phone   name  by id
        BizMerchantEntry bizMerchantEntry1 = bizMerchantEntryService.selectBizMerchantEntry(merchantBindingTerminalDTO.getId());
            //查设备  有没有设备  查激活  有没有激活  查报件 有没有报件
            if (!"".equals(merchantBindingTerminalDTO.getSn()) && merchantBindingTerminalDTO.getId() != null && !"".equals(merchantBindingTerminalDTO.getMerchId())) {
                BizPosMachine bizPosMachine = iBizPosMachineService.selectPosBySnCode(merchantBindingTerminalDTO.getSn());  //设备
                BizPosMachineStatusRecords bizPosMachineStatusRecords = machineStatusRecordsService.selectBizPosMachineStatusRecordsBysnCode(merchantBindingTerminalDTO.getSn());//激活
                BizMerchantEntry bizMerchantEntryBySn = bizMerchantEntryService.getBizMerchantEntryBySn(merchantBindingTerminalDTO.getSn());//报件
                if (bizPosMachine == null) {
                    return AjaxResult.error("没有该设备不能绑定");
                }
                if (bizPosMachineStatusRecords != null) {
                    return AjaxResult.error("设备已激活 不能绑定");
                }
                if (bizMerchantEntryBySn != null) {
                    return AjaxResult.error("设备已报件 不能绑定");
                }
                String OUTMER = "OUTMER";
                String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=terminalinfoDao&Methods=add";
                Map<String, String> data = new HashMap<String, String>();
                data.put("merchant_no", bizMerchantEntry1.getMerchantNo());
                data.put("sn", merchantBindingTerminalDTO.getSn());
                data.put("mersource", OUTMER);
                data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
                data.put("key", bizAgentidAppkeyDTO.getKey());
                data.put("sign", PosOneUtil.generateSignature(data));
                System.out.println("----------" + PosOneUtil.generateSignature(data));
                System.out.println("---------" + data);
                String result = HttpClientHandler.noPictureRequest(url, data);
                System.out.println("返回:" + result);
                JSONObject jsonObject = JSONObject.parseObject(result);
                String retCode = jsonObject.getString("ret_code");
                if (retCode.equals("0")) {//成功走咱们自己的业务
                    //2激活表新增数据
                    BizPosMachineStatusRecords bizPosMachineStatusRecords1 = new BizPosMachineStatusRecords();
                    bizPosMachineStatusRecords1.setMerchantId(bizMerchantEntry1.getMerchId().toString());
                    bizPosMachineStatusRecords1.setPhoneNo(bizMerchantEntry1.getPhone());
                    bizPosMachineStatusRecords1.setName(bizMerchantEntry1.getApplicant());
                    bizPosMachineStatusRecords1.setActiveTime(df.format(new Date()));
                    bizPosMachineStatusRecords1.setSnCode(merchantBindingTerminalDTO.getSn());
                    bizPosMachineStatusRecords1.setTime(df.format(new Date()));
                    machineStatusRecordsService.insertBizPosMachineStatusRecords(bizPosMachineStatusRecords1);
                    //3 设备表更新已激活 还要绑定merchid
                    iBizPosMachineService.updatebizPosMachineMerchIdAndStatus(merchantBindingTerminalDTO.getSn(), bizMerchantEntry1.getMerchId());
                    /***  在这里写新的 在另一个表里存sn还有报件的id  *****/
                    BizMerchantEntry bizMerchantEntry=new BizMerchantEntry();
                    bizMerchantEntry.setId(merchantBindingTerminalDTO.getId());
                    bizMerchantEntry.setSn(merchantBindingTerminalDTO.getSn());
                    bizMerchantEntry.setCreateTime(df.format(date));
                    iBizMerchantEntryService.insertBizEntrySn(bizMerchantEntry);
                    bizPosMachineMapper.generateAllPosMerchantRelatedProcedure();// 运行函数
                    //查询流量费收取列表
                    //bizFeesChargedService.timerGetChargeList(merchantBindingTerminalDTO.getSn());
                    return AjaxResult.success("绑定成功  开心      ------");
                } else {
                    System.out.println("---------------");
                    System.out.println("---------------" + result);
                    System.out.println("---------------");
                    return AjaxResult.error("接口返回失败了" + result);
                }
            } else {
                return AjaxResult.error("绑定失败");
            }
    }

    public final void relieve(String snCode){
        String fictitiousSnCode = "";
        //获取merchId merchName
        BizMerchant bizMerchant = iBizMerchantService.selectBizMerchantBySN(snCode);
        //生成虚拟sn
        fictitiousSnCode = IdWorker.getIdStr();
        //把虚拟sn存入设备表
        iBizPosMachineService.insertPosMachine(fictitiousSnCode, bizMerchant.getMerchId());
        //获取该sn所有交易记录
        List<BizMerchTransactions> list = BizMerchTransactionsService.selectBizMerchTransactions(snCode);
        if (list.size() > 0) {
            //把所有交易记录存入到解绑交易记录表
            BizMerchTransactionsService.insertbizMerchTransactionsUnbund(list, bizMerchant.getMerchId(), bizMerchant.getMerchName());
            //交易记录sn换成虚拟sn
            BizMerchTransactionsService.updateBizMerchTransactionsBySN(snCode, fictitiousSnCode);
        }
        //获取激活信息  存解绑记录
        BizPosMachineStatusRecords bizPosMachineStatusRecords = machineStatusRecordsService.selectBizPosMachineStatusRecordsBysnCode(snCode);
        if(null!=bizPosMachineStatusRecords){
            machineStatusRecordsService.insertBizPosRecordsNew(bizPosMachineStatusRecords);
        }
        //删除激活表该sn数据
        machineStatusRecordsService.deleteBizPosRecordsNew(snCode);
        //删除报件 设备
        machineStatusRecordsService.deletebizentrySn(snCode);
        //设备状态改为0
        iBizMerchantService.updataMerchantStatus(snCode);
        //运行函数
//        iBizMerchantService.generateAllPosMerchantRelatedProcedure();
    }

    /**
     * @author Wangjiaqi
     * @date 2022/02/28
     * POS设备入库
     */
    @PostMapping("/posThemDisPlayedAdd")
    @Transactional
    public AjaxResult themdisplayedAdd(@RequestBody PosTheMdisPlayDTO posTheMdisPlayDTO) throws Exception {
            AjaxResult ajaxResult=AjaxResult.success("");
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
                String OUTMER = "OUTMER";
                String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=posinfoDao&Methods=add";
                Map<String, String> data = new HashMap<String, String>();
                data.put("manufacturers_id", posTheMdisPlayDTO.getAname());
                data.put("device_type", posTheMdisPlayDTO.getBname());
                data.put("model_id", posTheMdisPlayDTO.getOname());
                data.put("sn", posTheMdisPlayDTO.getPosCode());
                data.put("sim_amt", posTheMdisPlayDTO.getSimAmt());
                data.put("sim_daynum", posTheMdisPlayDTO.getSimDaynum());
                if (posTheMdisPlayDTO.getSimIccid()!=null){
                    data.put("sim_iccid", posTheMdisPlayDTO.getSimIccid());
                }
                if (posTheMdisPlayDTO.getDevImei()!=null){
                    data.put("dev_imei", posTheMdisPlayDTO.getDevImei());
                }
                if (posTheMdisPlayDTO.getAccountId()!=null){
                    data.put("account_id", posTheMdisPlayDTO.getAccountId());
                }
                data.put("pos_canal", posTheMdisPlayDTO.getChannel());
                data.put("mersource", OUTMER);
                data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
                data.put("key", bizAgentidAppkeyDTO.getKey());
                data.put("sign", PosOneUtil.generateSignature(data));
                System.out.println("----------" + PosOneUtil.generateSignature(data));
                System.out.println("---------" + data);
                String result = HttpClientHandler.noPictureRequest(url, data);
                System.out.println("返回:" + result);
                JSONObject jsonObject = JSONObject.parseObject(result);
                String retCode = jsonObject.getString("ret_code");
                String retMsge = jsonObject.getString("ret_msge");
                if (retCode.equals("0")){
                    JSONObject data1 = jsonObject.getJSONObject("data");
                    BizPosMachine bizPosMachine2=new BizPosMachine();
                    String posType = posMachineMapper.selectPosType(posTheMdisPlayDTO.getPosCode());
                    if (posType==null || "".equals(posType)){
                        bizPosMachine2.setPosType("9");
                    }
                    String var1 = posMachineMapper.selectVar1(bizPosMachine2.getVar1());
                    bizPosMachine2.setVar1(var1);
                    bizPosMachine2.setPosCode(posTheMdisPlayDTO.getPosCode());
                    bizPosMachine2.setPosName("直联POS");
                    bizPosMachine2.setPosType("19");
                    /*bizPosMachine2.setPosActivateCode(posTheMdisPlayDTO.getPosActivateCode());*/
                    bizPosMachine2.setPosActivateStatus("0");
                    bizPosMachine2.setTerminalNo(data1.getString("terminal_no"));
                    /*bizPosMachine2.setPosBindTime(bizPosMachine1.getCreateTime());*/
                    /*bizPosMachine2.setPosActivity(bizPosMachine1.getPosActivity());
                    bizPosMachine2.setPosDeposit(bizPosMachine1.getPosDeposit());
                    bizPosMachine2.setPosCashback(bizPosMachine1.getPosCashback());
                    bizPosMachine2.setPosModel(bizPosMachine1.getPosModel());*/
                    bizPosMachine2.setMerchId(Long.valueOf(posTheMdisPlayDTO.getMerchName()));
                    /*bizPosMachine2.setCreateTime(bizPosMachine1.getCreateTime());
                    bizPosMachine2.setUpdateTime(bizPosMachine1.getCreateTime());
                    bizPosMachine2.setVar2(bizPosMachine1.getVar2());
                     */
                    bizPosMachine2.setManufacturersId(posTheMdisPlayDTO.getAname());
                    bizPosMachine2.setDeviceType(posTheMdisPlayDTO.getBname());
                    bizPosMachine2.setModelId(posTheMdisPlayDTO.getOname());
                    bizPosMachine2.setSimAmt(posTheMdisPlayDTO.getSimAmt());
                    bizPosMachine2.setSimDaynum(posTheMdisPlayDTO.getSimDaynum());
                    bizPosMachine2.setSimIccid(posTheMdisPlayDTO.getSimIccid());
                    bizPosMachine2.setDevImei(posTheMdisPlayDTO.getDevImei());
                    bizPosMachine2.setChannel(posTheMdisPlayDTO.getChannel());
                    int row=posMachineMapper.insertPosMachine(bizPosMachine2);
                    Long merchId =bizMerchantEntryService.setBizPlatformSync(SecurityUtils.getLoginUser().getUser().getUserId());
                    if(merchId!=null){
                        bizPosMachine2.setMerchId(merchId);
                        sendSlmThemdisplayedAdd(bizPosMachine2);
                    }
                    ajaxResult.put("retCode",true);
                    ajaxResult.put("retMsge",retMsge);
            }else {
                    ajaxResult.put("retCode",false);
                    ajaxResult.put("retMsge",retMsge);
                }
            return ajaxResult;
    }

    /**
     * @author Wangjiaqi
     * @date 2022/02/28
     *      POS设备入库---直联新增
     */
    @PreAuthorize("@ss.hasPermi('terminal:posmachine:add')")
    @PostMapping("/posThemDisPlayedOldAdd")
    @Transactional
    public AjaxResult themdisplayedOldAdd(@RequestBody PosTheMdisPlayDTO posTheMdisPlayDTO) throws Exception {
            AjaxResult ajaxResult=AjaxResult.success("");
            BizPosMachine b=posMachineMapper.selectPosMachine(posTheMdisPlayDTO.getPosCode());
            if (b==null){
                BizPosMachine bizPosMachine2=new BizPosMachine();
                String var1 = posMachineMapper.selectVar1(bizPosMachine2.getVar1());
                BizPosType bizPosType = posMachineMapper.selectType(Long.valueOf(posTheMdisPlayDTO.getPosType()));
                bizPosMachine2.setVar1(var1);
                bizPosMachine2.setPosCode(posTheMdisPlayDTO.getPosCode());
                bizPosMachine2.setPosName(bizPosType.getTypeName());
                bizPosMachine2.setPosType(posTheMdisPlayDTO.getPosType());
                bizPosMachine2.setPosActivateStatus("0");
                bizPosMachine2.setMerchId(Long.valueOf(posTheMdisPlayDTO.getMerchName()));
                bizPosMachine2.setModelId(posTheMdisPlayDTO.getModelId());
                int row=posMachineMapper.insertPosMachine(bizPosMachine2);
                ajaxResult.put("code",200);
                ajaxResult.put("msg","入库成功");
                return ajaxResult;
            }else {
                ajaxResult.put("code",500);
                ajaxResult.put("msg","入库失败，已存在，不能入库");
                return ajaxResult;
            }
    }

    /**
     * @author Wangjiaqi
     * @date 2022/02/28
     * 12、POS设备列表
     */
    @PostMapping("/posThemDisPlayedList")
    @Transactional
    public PosThemDisPlayedDTO themdisplayedList(@RequestBody PosTheMdisPlayDTO posTheMdisPlayDTO) throws Exception {
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        String OUTMER = "OUTMER";
        if (posTheMdisPlayDTO.getSn()!=null){
            //列表
            String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=posinfoDao&Methods=list";
            Map<String, String> data = new HashMap<String, String>();
            if (posTheMdisPlayDTO.getNamenames()!=null){
                data.put("namenames", posTheMdisPlayDTO.getNamenames());
            }
            if (posTheMdisPlayDTO.getSn()!=null){
                data.put("sn", posTheMdisPlayDTO.getSn());
            }
            if (posTheMdisPlayDTO.getManufacturersId()!=null){
                data.put("manufacturers_id", posTheMdisPlayDTO.getManufacturersId());
            }
            if (posTheMdisPlayDTO.getAddDate()!=null){
                data.put("add_date", posTheMdisPlayDTO.getAddDate());
            }
            if (posTheMdisPlayDTO.getDevStatus()!=null){
                data.put("dev_status", posTheMdisPlayDTO.getDevStatus());
            }
            if (posTheMdisPlayDTO.getPageNum()!=null){
                data.put("start", posTheMdisPlayDTO.getPageNum());
            }else {
                data.put("start", "1");
            }
            if (posTheMdisPlayDTO.getPageSize()!=null){
                data.put("limit", posTheMdisPlayDTO.getPageSize());
            }else {
                data.put("limit", "1");
            }
            data.put("mersource", OUTMER);
            data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
            data.put("key", bizAgentidAppkeyDTO.getKey());
            data.put("sign", PosOneUtil.generateSignature(data));
            System.out.println("----------" + PosOneUtil.generateSignature(data));
            System.out.println("---------" + data);
            String result = HttpClientHandler.noPictureRequest(url, data);
            System.out.println("返回:" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String retCode = jsonObject.getString("ret_code");
            String retMsge = jsonObject.getString("ret_msge");
            //data返回值
            PosThemDisPlayedDTO posThemDisPlayedDTO=new PosThemDisPlayedDTO();
            if (retCode.equals("0")) {
                //list  返回值
                List<PosThemDisPlayedReturnDTO> posThemDisPlayedReturnDTOS =new ArrayList<PosThemDisPlayedReturnDTO>();
                JSONObject data1 = jsonObject.getJSONObject("data");
                JSONArray list1 = data1.getJSONArray("list");
                Integer totcount = data1.getInteger("totcount");
                posThemDisPlayedDTO.setTotcount(totcount);
                posThemDisPlayedDTO.setPosThemDisPlayedReturnDTOS(posThemDisPlayedReturnDTOS);
                for (int i = 0; i < list1.size(); i++) {
                    JSONObject jsonObject1 = list1.getJSONObject(i);
                    PosThemDisPlayedReturnDTO posThemDisPlayedReturnDTO=new PosThemDisPlayedReturnDTO();
                    posThemDisPlayedReturnDTO.setOrgnname(jsonObject1.getString("orgnname"));
                    posThemDisPlayedReturnDTO.setManufaname(jsonObject1.getString("manufaname"));
                    posThemDisPlayedReturnDTO.setModelName(jsonObject1.getString("model_name"));
                    posThemDisPlayedReturnDTO.setSn(jsonObject1.getString("sn"));
                    posThemDisPlayedReturnDTO.setTerminalNo(jsonObject1.getString("terminal_no"));
                    posThemDisPlayedReturnDTO.setAddDate(jsonObject1.getString("add_date"));
                    posThemDisPlayedReturnDTO.setDevStatus(jsonObject1.getString("dev_status"));
                    posThemDisPlayedReturnDTO.setMerchantNo(jsonObject1.getString("merchant_no"));
                    posThemDisPlayedReturnDTO.setAcqName(jsonObject1.getString("acq_name"));
                    posThemDisPlayedReturnDTO.setBuildDate(jsonObject1.getString("build_date"));
                    posThemDisPlayedReturnDTO.setBindDate(jsonObject1.getString("bind_date"));
                    if(!posThemDisPlayedReturnDTO.getAddDate().equals("")){
                        StringBuilder stringAddDate=new StringBuilder(posThemDisPlayedReturnDTO.getAddDate());
                        stringAddDate.insert(4,"-");
                        stringAddDate.insert(7,"-");
                        posThemDisPlayedReturnDTO.setAddDate(stringAddDate.toString());
                    }
                    if (!posThemDisPlayedReturnDTO.getBindDate().equals("")){
                        StringBuilder stringBindDate=new StringBuilder(posThemDisPlayedReturnDTO.getBindDate());
                        stringBindDate.insert(4,"-");
                        stringBindDate.insert(7,"-");
                        posThemDisPlayedReturnDTO.setBindDate(stringBindDate.toString());
                    }
                    posThemDisPlayedReturnDTOS.add(posThemDisPlayedReturnDTO);
                }
            }
            return posThemDisPlayedDTO;
        }else {
            //搜素
            String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=posinfoDao&Methods=load";
            Map<String, String> data = new HashMap<String, String>();
            data.put("sn", posTheMdisPlayDTO.getSn());
            data.put("terminal_no", posTheMdisPlayDTO.getTerminalNo());
            data.put("mersource", OUTMER);
            data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
            data.put("key", bizAgentidAppkeyDTO.getKey());
            data.put("sign", PosOneUtil.generateSignature(data));
            System.out.println("----------" + PosOneUtil.generateSignature(data));
            System.out.println("---------" + data);
            String result = HttpClientHandler.noPictureRequest(url, data);
            System.out.println("返回:" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String retCode = jsonObject.getString("ret_code");
            String retMsge = jsonObject.getString("ret_msge");
            PosThemDisPlayedDTO posThemDisPlayedDTO=new PosThemDisPlayedDTO();
            if (retCode.equals("0")) {
                List<PosThemDisPlayedReturnDTO> posThemDisPlayedReturnDTOS =new ArrayList<PosThemDisPlayedReturnDTO>();
                posThemDisPlayedDTO.setTotcount(1);
                posThemDisPlayedDTO.setPosThemDisPlayedReturnDTOS(posThemDisPlayedReturnDTOS);
                PosThemDisPlayedReturnDTO posThemDisPlayedReturnDTO=new PosThemDisPlayedReturnDTO();
                JSONObject dara1 = jsonObject.getJSONObject("data");
                posThemDisPlayedReturnDTO.setOrgnname( dara1.getString("orgnname"));
                posThemDisPlayedReturnDTO.setManufacturersId( dara1.getString("manufacturers_id"));
                posThemDisPlayedReturnDTO.setManufaname( dara1.getString("manufaname"));
                posThemDisPlayedReturnDTO.setDeviceType( dara1.getString("device_type"));
                posThemDisPlayedReturnDTO.setModelName( dara1.getString("model_name"));
                posThemDisPlayedReturnDTO.setSn( dara1.getString("sn"));
                posThemDisPlayedReturnDTO.setTerminalNo( dara1.getString("terminal_no"));
                posThemDisPlayedReturnDTO.setSimAmt( dara1.getString("sim_amt"));
                posThemDisPlayedReturnDTO.setAddDate( dara1.getString("add_date"));
                posThemDisPlayedReturnDTO.setDevStatus( dara1.getString("dev_status"));
                posThemDisPlayedReturnDTO.setAppType( dara1.getString("app_type"));
                posThemDisPlayedReturnDTO.setSimIccid( dara1.getString("sim_iccid"));
                posThemDisPlayedReturnDTO.setDevImei( dara1.getString("dev_imei"));
                posThemDisPlayedReturnDTOS.add(posThemDisPlayedReturnDTO);
            }
            return posThemDisPlayedDTO;
        }
    }

    /**
     * @author Wangjiaqi
     * @date 2022/02/28 .
     * 14、POS设备修改···
     */
    @PostMapping("/posThemDisPlayedUpdate")
    @Transactional
    public AjaxResult themdisplayedUpdate(@RequestBody PosTheMdisPlayDTO posTheMdisPlayDTO) throws Exception {
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        AjaxResult ajaxResult=AjaxResult.success("修改成功");
        String OUTMER = "OUTMER";
        String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=posinfoDao&Methods=update";
        Map<String, String> data = new HashMap<String, String>();
        data.put("terminal_no", posTheMdisPlayDTO.getTerminalNo());
        data.put("manufacturers_id", posTheMdisPlayDTO.getManufacturersId());
        data.put("device_type", posTheMdisPlayDTO.getDeviceType());
        data.put("model_id", posTheMdisPlayDTO.getModelId());
        data.put("sn", posTheMdisPlayDTO.getPosCode());
        data.put("sim_amt", posTheMdisPlayDTO.getSimAmt());
        data.put("sim_daynum", posTheMdisPlayDTO.getSimDaynum());
        if (posTheMdisPlayDTO.getSimIccid()!=null){
            data.put("sim_iccid", posTheMdisPlayDTO.getSimIccid());
        }
        if (posTheMdisPlayDTO.getDevImei()!=null){
            data.put("dev_imei", posTheMdisPlayDTO.getDevImei());
        }
        if (posTheMdisPlayDTO.getAccountId()!=null){
            data.put("account_id", posTheMdisPlayDTO.getAccountId());
        }
        data.put("pos_canal",posTheMdisPlayDTO.getChannel());
        data.put("mersource", OUTMER);
        data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        data.put("key", bizAgentidAppkeyDTO.getKey());
        data.put("sign", PosOneUtil.generateSignature(data));
        System.out.println("----------" + PosOneUtil.generateSignature(data));
        System.out.println("---------" + data);
        String result = HttpClientHandler.noPictureRequest(url, data);
        System.out.println("返回:" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String retCode = jsonObject.getString("ret_code");
        String retMsge = jsonObject.getString("ret_msge");
        if (retCode.equals("0")){
            BizPosMachine bizPosMachine2=new BizPosMachine();
            String var1 = posMachineMapper.selectVar1(bizPosMachine2.getVar1());
            bizPosMachine2.setVar1(var1);
            bizPosMachine2.setPosCode(posTheMdisPlayDTO.getPosCode());
            bizPosMachine2.setPosName("直联POS");
            bizPosMachine2.setPosType("19");
            bizPosMachine2.setPosActivateStatus("0");
            bizPosMachine2.setMerchId(Long.valueOf(posTheMdisPlayDTO.getMerchName()));
            bizPosMachine2.setManufacturersId(posTheMdisPlayDTO.getManufacturersId());
            bizPosMachine2.setDeviceType(posTheMdisPlayDTO.getDeviceType());
            bizPosMachine2.setModelId(posTheMdisPlayDTO.getModelId());
            bizPosMachine2.setSimAmt(posTheMdisPlayDTO.getSimAmt());
            bizPosMachine2.setSimDaynum(posTheMdisPlayDTO.getSimDaynum());
            bizPosMachine2.setSimIccid(posTheMdisPlayDTO.getSimIccid());
            bizPosMachine2.setDevImei(posTheMdisPlayDTO.getDevImei());
            bizPosMachine2.setPosId(posTheMdisPlayDTO.getPosId());
            bizPosMachine2.setChannel(posTheMdisPlayDTO.getChannel());
            int row=posMachineMapper.updateSyncPosMachine(bizPosMachine2);
            ajaxResult.put("retCode",true);
            ajaxResult.put("retMsge",retMsge);
            return ajaxResult;
        }else {
            ajaxResult.put("retCode",false);
            ajaxResult.put("retMsge",retMsge);
            return ajaxResult;
        }
    }

    /**
     * @author Wangjiaqi
     * @date 2022/02/28
     * 15、POS设备删除
     */
    @PostMapping("/posThemDisPlayedDel")
    @Transactional
    public AjaxResult themdisplayedDel(@RequestBody PosTheMdisPlayDTO posTheMdisPlayDTO) throws Exception {
//        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        AjaxResult ajaxResult=AjaxResult.success("删除成功");
        //删除设备
        posMachineMapper.delBizPosMachine(posTheMdisPlayDTO.getSn());
        // 删除政策
        //删除总平台设备
        return ajaxResult;
    }
//        String OUTMER = "OUTMER";
//        String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=posinfoDao&Methods=del";
//        Map<String, String> data = new HashMap<String, String>();
//        data.put("terminal_no", posTheMdisPlayDTO.getTerminalNo());
//        data.put("sn", posTheMdisPlayDTO.getSn());
//        if (posTheMdisPlayDTO.getAccountId()!=null){
//            data.put("account_id", posTheMdisPlayDTO.getAccountId());
//        }
//        data.put("mersource", OUTMER);
//        data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
//        data.put("key", bizAgentidAppkeyDTO.getKey());
//        data.put("sign", PosOneUtil.generateSignature(data));
//        System.out.println("----------" + PosOneUtil.generateSignature(data));
//        System.out.println("---------" + data);
//        String result = HttpClientHandler.noPictureRequest(url, data);
//        System.out.println("返回:" + result);
//        JSONObject jsonObject = JSONObject.parseObject(result);
//        String retCode = jsonObject.getString("ret_code");
//        String retMsge = jsonObject.getString("ret_msge");
//        if (retCode.equals("0")){
//            ajaxResult.put("retCode",true);
//            ajaxResult.put("retMsge",retMsge);
//        }else {
//            ajaxResult.put("retCode",false);
//            ajaxResult.put("retMsge",retMsge);
//        }

    /**
     * @author Wangjiaqi
     * @date 2022/02/28
     * 16、费用收取添加
     */
    @PostMapping("/posSaInPassFeesAdd")
    @Transactional
    public AjaxResult posSaInPassFeesAdd(@RequestBody SaInPassFeesDTO saInPassFeesDTO) throws Exception {
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        AjaxResult ajaxResult=AjaxResult.success();
        String OUTMER = "OUTMER";
        String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=teramtDao&Methods=add";
        Map<String, String> data = new HashMap<String, String>();
        data.put("merchant_no", saInPassFeesDTO.getMerchantNo());
        data.put("sn", saInPassFeesDTO.getSn());
        data.put("amt", saInPassFeesDTO.getAmt());
        data.put("amt_type", saInPassFeesDTO.getAmtType());
        data.put("date_type", saInPassFeesDTO.getDateType());
        if (saInPassFeesDTO.getAccountId()==null){
            data.put("account_id", saInPassFeesDTO.getAccountId());
        }
        data.put("mersource", OUTMER);
        data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        data.put("key", bizAgentidAppkeyDTO.getKey());
        data.put("sign", PosOneUtil.generateSignature(data));
        System.out.println("----------" + PosOneUtil.generateSignature(data));
        System.out.println("---------" + data);
        /*String result = HttpClientHandler.noPictureRequest(url, data);
        System.out.println("返回:" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String retCode = jsonObject.getString("ret_code");
        String retMsge = jsonObject.getString("ret_msge");*/
        String retCode = "0";
        if (retCode.equals("0")){
            //JSONObject data1 = jsonObject.getJSONObject("data");
            BizFeesChargedAddDTO bizFeesChargedAddDTO=new BizFeesChargedAddDTO();
            bizFeesChargedAddDTO.setMerchantNo(saInPassFeesDTO.getMerchantNo());
            bizFeesChargedAddDTO.setSn(saInPassFeesDTO.getSn());
            bizFeesChargedAddDTO.setAmt(saInPassFeesDTO.getAmt());
            bizFeesChargedAddDTO.setAmtType(saInPassFeesDTO.getAmtType());
            bizFeesChargedAddDTO.setAccountId(saInPassFeesDTO.getAccountId());
            bizFeesChargedAddDTO.setDateType(saInPassFeesDTO.getDateType());
            //bizFeesChargedAddDTO.setMamountId(data1.getString("mamount_id"));
            int row=posMachineMapper.insertBizFeesChargedAdd(bizFeesChargedAddDTO);
            if (row>0){
                ajaxResult.put("retCode",true);
                ajaxResult.put("retMsge","成功");
                //ajaxResult.put("retMsge",retMsge);
            }else {
                ajaxResult.put("retCode",true);
                ajaxResult.put("retMsge","提交成功，添加失败");
            }
        }else {
            ajaxResult.put("retCode",false);
            ajaxResult.put("retMsge","失败");
            //ajaxResult.put("retMsge",retMsge);
        }
        return ajaxResult;
    }

    /**
     * @author Wangjiaqi
     * @date 2022/02/28
     * 17、费用收取列表
     */
    @PostMapping("/posSaInPassFeesList")
    @Transactional
    public SaInPassFeesReturnDTO posSaInPassFeesList(@RequestBody SaInPassFeesDTO saInPassFeesDTO) throws Exception {
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        String OUTMER = "OUTMER";
        if (saInPassFeesDTO.getMamountId()==null){
            String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=teramtDao&Methods=list";
            Map<String, String> data = new HashMap<String, String>();
            if (saInPassFeesDTO.getSn()!=null){
                data.put("sn", saInPassFeesDTO.getSn());
            }
            if (saInPassFeesDTO.getMerInfo()!=null){
                data.put("mer_info", saInPassFeesDTO.getMerInfo());
            }
            if (saInPassFeesDTO.getCreatdate()!=null){
                data.put("creatdate", saInPassFeesDTO.getCreatdate());
            }
            if (saInPassFeesDTO.getStartsType()!=null){
                data.put("starts_type", saInPassFeesDTO.getStartsType());
            }
            if (saInPassFeesDTO.getPageNum()==null){
                data.put("start", "1");
            }else {
                data.put("start", saInPassFeesDTO.getPageNum());
            }
            if (saInPassFeesDTO.getPageSize()==null){
                data.put("limit", "1");
            }else {
                data.put("limit", saInPassFeesDTO.getPageSize());
            }
            data.put("mersource", OUTMER);
            data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
            data.put("key", bizAgentidAppkeyDTO.getKey());
            data.put("sign", PosOneUtil.generateSignature(data));
            System.out.println("----------" + PosOneUtil.generateSignature(data));
            System.out.println("---------" + data);
            String result = HttpClientHandler.noPictureRequest(url, data);
            System.out.println("返回:" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String retCode = jsonObject.getString("ret_code");
            String retMsge = jsonObject.getString("ret_msge");
            SaInPassFeesReturnDTO saInPassFeesReturnDTO=new SaInPassFeesReturnDTO();
            if (retCode.equals("0")) {
                List<SaInPassFeesDTO> saInPassFeesDTOS =new ArrayList<SaInPassFeesDTO>();
                JSONObject data1 = jsonObject.getJSONObject("data");
                Integer totcount = data1.getInteger("totcount");
                JSONArray list1 = data1.getJSONArray("list");
                saInPassFeesReturnDTO.setTotcount(totcount);
                saInPassFeesReturnDTO.setSaInPassFeesDTOS(saInPassFeesDTOS);
                for (int i = 0; i < list1.size(); i++) {
                    JSONObject jsonObject1 = list1.getJSONObject(i);
                    SaInPassFeesDTO saInPassFeesDTO1=new SaInPassFeesDTO();
                    saInPassFeesDTO1.setOrgnname(jsonObject1.getString("orgnname"));
                    saInPassFeesDTO1.setMamountId(jsonObject1.getString("mamount_id"));
                    saInPassFeesDTO1.setMerchantNo(jsonObject1.getString("merchant_no"));
                    saInPassFeesDTO1.setSn(jsonObject1.getString("sn"));
                    saInPassFeesDTO1.setSimcardfee(jsonObject1.getString("simcardfee"));
                    saInPassFeesDTO1.setMamountStarts(jsonObject1.getString("mamount_starts"));
                    saInPassFeesDTO1.setOrderNo(jsonObject1.getString("order_no"));
                    saInPassFeesDTO1.setAmtType(jsonObject1.getString("amt_type"));
                    saInPassFeesDTO1.setCreatdate(jsonObject1.getString("creatdate"));
                    saInPassFeesDTO1.setHostDate(jsonObject1.getString("host_date"));
                    StringBuilder stringCreatdate=new StringBuilder(saInPassFeesDTO1.getCreatdate());
                    stringCreatdate.insert(4,"-");
                    stringCreatdate.insert(7,"-");
                    stringCreatdate.insert(10," ");
                    stringCreatdate.insert(13,":");
                    stringCreatdate.insert(16,":");
                    saInPassFeesDTO1.setCreatdate(stringCreatdate.toString());
                    if (!saInPassFeesDTO1.getHostDate().equals("")){
                        StringBuilder stringHostDate=new StringBuilder(saInPassFeesDTO1.getHostDate());
                        stringHostDate.insert(4,"-");
                        stringHostDate.insert(7,"-");
                        saInPassFeesDTO1.setHostDate(stringHostDate.toString());
                    }
                    saInPassFeesDTOS.add(saInPassFeesDTO1);
                }
            }
            return saInPassFeesReturnDTO;
        }else {
            String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=teramtDao&Methods=load";
            Map<String, String> data = new HashMap<String, String>();
            data.put("mamount_id", saInPassFeesDTO.getMamountId());
            data.put("mersource", OUTMER);
            data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
            data.put("key", bizAgentidAppkeyDTO.getKey());
            data.put("sign", PosOneUtil.generateSignature(data));
            System.out.println("----------" + PosOneUtil.generateSignature(data));
            System.out.println("---------" + data);
            String result = HttpClientHandler.noPictureRequest(url, data);
            System.out.println("返回:" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String retCode = jsonObject.getString("ret_code");
            String retMsge = jsonObject.getString("ret_msge");
            SaInPassFeesReturnDTO saInPassFeesReturnDTO=new SaInPassFeesReturnDTO();
            if (retCode.equals("0")) {
                List<SaInPassFeesDTO> passFeesDTOS =new ArrayList<SaInPassFeesDTO>();
                saInPassFeesReturnDTO.setTotcount(1);
                saInPassFeesReturnDTO.setSaInPassFeesDTOS(passFeesDTOS);
                SaInPassFeesDTO saInPassFeesDTO1=new SaInPassFeesDTO();
                JSONObject dara1 = jsonObject.getJSONObject("data");
                saInPassFeesDTO1.setMamountId(dara1.getString("mamount_id"));
                saInPassFeesDTO1.setOrgnname(dara1.getString("orgnname"));
                saInPassFeesDTO1.setMerchantNo(dara1.getString("merchant_no"));
                saInPassFeesDTO1.setSn(dara1.getString("sn"));
                saInPassFeesDTO1.setSimcardfee(dara1.getString("simcardfee"));
                saInPassFeesDTO1.setMamountStartsName(dara1.getString("mamount_starts_name"));
                saInPassFeesDTO1.setOrderNo(dara1.getString("order_no"));
                saInPassFeesDTO1.setAmtTypeName(dara1.getString("amt_type_name"));
                saInPassFeesDTO1.setCreatdate(dara1.getString("creatdate"));
                saInPassFeesDTO1.setDateType(dara1.getString("date_type"));
                saInPassFeesDTO1.setDateColl(dara1.getString("date_coll"));
                passFeesDTOS.add(saInPassFeesDTO1);
            }
            return saInPassFeesReturnDTO;
        }
    }

    /**
     * @author Wangjiaqi
     * @date 2022/02/28
     * 19、费用收取取消
     */
    @PostMapping("/posSaInPassFeesDel")
    @Transactional
    public AjaxResult SaInPassFeesDel(@RequestBody PosTheMdisPlayDTO posTheMdisPlayDTO) throws Exception {
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        AjaxResult ajaxResult = AjaxResult.success();
        String OUTMER = "OUTMER";
        String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=teramtDao&Methods=del";
        Map<String, String> data = new HashMap<String, String>();
        data.put("mamount_id", posTheMdisPlayDTO.getMamountId());
        data.put("account_id", posTheMdisPlayDTO.getAccountId());
        data.put("mersource", OUTMER);
        data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        data.put("key", bizAgentidAppkeyDTO.getKey());
        data.put("sign", PosOneUtil.generateSignature(data));
        System.out.println("----------" + PosOneUtil.generateSignature(data));
        System.out.println("---------" + data);
        String result = HttpClientHandler.noPictureRequest(url, data);
        System.out.println("返回:" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String retCode = jsonObject.getString("ret_code");
        String retMsge = jsonObject.getString("ret_msge");
        if (retCode.equals("0")) {
            ajaxResult.put("retCode",retCode);
            ajaxResult.put("retMsge",retMsge);
        }
        return ajaxResult;
    }

    /**
     * @author Wangjiaqi
     * @date 2022/02/28
     * 20、品牌型号查询列表
     */
    @PostMapping("/BrandModelList")
    @Transactional
    public AjaxResult BrandModelList(@RequestBody PosTheMdisPlayDTO posTheMdisPlayDTO) throws Exception {
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        AjaxResult ajaxResult = AjaxResult.success();
        if(bizAgentidAppkeyDTO == null){
            return AjaxResult.success();
        }
        String OUTMER = "OUTMER";
        String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=wsmodeDao&Methods=list";
        Map<String, String> data = new HashMap<String, String>();
        data.put("man_type", posTheMdisPlayDTO.getManType());
        if (!posTheMdisPlayDTO.getManType().equals("1")){
            data.put("man_info", posTheMdisPlayDTO.getManInfo());
        }
        data.put("mersource", OUTMER);
        data.put("agentid",bizAgentidAppkeyDTO.getAgentid());
        data.put("key", bizAgentidAppkeyDTO.getKey());
        data.put("sign", PosOneUtil.generateSignature(data));
        System.out.println("----------" + PosOneUtil.generateSignature(data));
        System.out.println("---------" + data);
        String result = HttpClientHandler.noPictureRequest(url, data);
        System.out.println("返回:" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String retCode = jsonObject.getString("ret_code");
        String retMsge = jsonObject.getString("ret_msge");
        if (retCode.equals("0")) {
            List<BrandModelDTO> brandModelDTO =new ArrayList<BrandModelDTO>();
            JSONObject data1 = jsonObject.getJSONObject("data");
            JSONArray list1 = data1.getJSONArray("list");
            for (int i = 0; i < list1.size(); i++) {
                JSONObject jsonObject1 = list1.getJSONObject(i);
                Object code =jsonObject1.getString("code");
                Object name =jsonObject1.getString("name");
                /*Object simType =jsonObject1.getString("sim_type");*/
                BrandModelDTO brandModelDTO1=new BrandModelDTO();
                brandModelDTO1.setCode(code.toString());
                brandModelDTO1.setName(name.toString());
                //brandModelDTO1.setManType(posTheMdisPlayDTO.getManType());
                //bizMerchantEntryMapper.insertBizBrandModel(brandModelDTO1);
                /*brandModelDTO1.setSimType(simType.toString());*/
                brandModelDTO.add(brandModelDTO1);
            }
            ajaxResult.put("list",brandModelDTO);
        }
        return ajaxResult;
    }

    /**
     * @author zhj
     * @date 2022/02/28
     * 21、SIM查询列表
     */
    @PostMapping("/simQueryList")
    @Transactional
    public AjaxResult BrandModelList(@RequestBody SimQueryDTO simQueryDTO) throws Exception {
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        AjaxResult ajaxResult=AjaxResult.success();
        String OUTMER = "OUTMER";
        String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=simcardDao&Methods=list";
        Map<String, String> data = new HashMap<String, String>();
        data.put("sim_zsix", simQueryDTO.getSimZsix());
        data.put("start", simQueryDTO.getStart());
        data.put("limit", simQueryDTO.getLimit());
        data.put("mersource", OUTMER);
        data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        data.put("key", bizAgentidAppkeyDTO.getKey());
        data.put("sign", PosOneUtil.generateSignature(data));
        System.out.println("----------" + PosOneUtil.generateSignature(data));
        System.out.println("---------" + data);
        String result = HttpClientHandler.noPictureRequest(url, data);
        System.out.println("返回:" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String retCode = jsonObject.getString("ret_code");
        String retMsge = jsonObject.getString("ret_msge");
        SimQueryReturnDTO simQueryReturnDTO=new SimQueryReturnDTO();
        if (retCode.equals("0")) {
            //list  返回值
            List<SimQueryDTO> simQueryDTOS =new ArrayList<SimQueryDTO>();
            JSONObject data1 = jsonObject.getJSONObject("data");
            JSONArray list1 = data1.getJSONArray("list");
            Integer totcount = data1.getInteger("totcount");
            if (totcount==0){
                ajaxResult.put("retCode",false);
                ajaxResult.put("retMsge","获取sim失败，请查看输入数据是否正确");
                return ajaxResult;
            }else {
                simQueryReturnDTO.setTotcount(totcount);
                simQueryReturnDTO.setSimQueryDTOS(simQueryDTOS);
                for (int i = 0; i < list1.size(); i++) {
                    JSONObject jsonObject1 = list1.getJSONObject(i);
                    SimQueryDTO simQueryDTO1=new SimQueryDTO();
                    simQueryDTO1.setSimIccid(jsonObject1.getString("sim_iccid"));
                    simQueryDTOS.add(simQueryDTO1);
                }
                ajaxResult.put("code",200);
                ajaxResult.put("retMsge","获取成功请点击下方下拉框，选择SIM");
                ajaxResult.put("data",simQueryReturnDTO);
                return ajaxResult;
            }
        }else {
            ajaxResult.put("retCode",false);
            ajaxResult.put("retMsge",retMsge);
            return ajaxResult;
        }
    }

    @PostMapping("/echoServer")
    public AjaxResult echoServer(@RequestBody BizMerchant bizMerchant) {
        AjaxResult ajaxResult = AjaxResult.success();
        List<BizeServerCharge> list = iBizMerchantService.echoServerBizServiceCharge();
        BizMerchantReturnMoney bizMerchantReturnMoney = iBizMerchantService.selectBizServiceCharge(bizMerchant.getUserId());
        list.get(0).setServerMoney(bizMerchantReturnMoney.getServerThirtySix());
        list.get(1).setServerMoney(bizMerchantReturnMoney.getServerFortyEight());
        list.get(2).setServerMoney(bizMerchantReturnMoney.getServerNinetyNine());
        list.get(3).setServerMoney(bizMerchantReturnMoney.getServerTwoNinetyNine());
        list.get(4).setServerMoney(bizMerchantReturnMoney.getFlowTwoFour());
        list.get(5).setServerMoney(bizMerchantReturnMoney.getFlowThirtySix());
        list.get(6).setServerMoney(bizMerchantReturnMoney.getFlowFortyEight());
        list.get(7).setServerMoney(bizMerchantReturnMoney.getFlowNinetyNine());
        list.get(8).setServerMoney(bizMerchantReturnMoney.getServerSixty());
        list.get(9).setServerMoney(bizMerchantReturnMoney.getServerOneNinetyNine());
        list.get(10).setServerMoney(bizMerchantReturnMoney.getServerFortyNine());
        list.get(11).setServerMoney(bizMerchantReturnMoney.getFlowSixty());
        list.get(12).setServerMoney(bizMerchantReturnMoney.getServerThreeNinetyNine());
        list.get(13).setServerMoney(bizMerchantReturnMoney.getServerTwoFour());
        list.get(14).setServerMoney(bizMerchantReturnMoney.getFlowSixtyHyb());
        list.get(15).setServerMoney(bizMerchantReturnMoney.getFlowSixtyLkl());
        ajaxResult.put("data", list);
        return ajaxResult;
    }


    /*@PostMapping("/test")

    /*用来把报件表的sn  拿出来   放入新的表*/
    @PostMapping("/test")
    public AjaxResult test() {
        List<BizMerchantEntry> bizMerchantEntry= iBizPosMachineService.selectEntryAll();
        for (BizMerchantEntry bizMerchantEntry1:bizMerchantEntry){
             bizMerchantEntryMapper.insertBizEntrySn(bizMerchantEntry1);
        }
        return AjaxResult.success();
    }

    /*查看pos1.0交易通知  没有分润的数据*/
    @PostMapping("/selectUuidIsNull")
    public AjaxResult selectUuidIsNull() {
        List<SynchronizationDataDTO> synchronizationDataDTOS=new ArrayList<SynchronizationDataDTO>();
        List<SynchronizationDataDTO> SynchronizationDataDTO= iBizPosMachineService.selectUuidIsNull();
        for (SynchronizationDataDTO bizMerchantEntry1:SynchronizationDataDTO){
            List<BizProfitDeatail> bizProfitDeatails = iBizPosMachineService.selectfenrun(bizMerchantEntry1.getUuid());
            if (bizProfitDeatails.size()==0){
                synchronizationDataDTOS.add(bizMerchantEntry1);
            }
        }
        return AjaxResult.success(synchronizationDataDTOS);
    }
    private String sendSlmThemdisplayedAdd(BizPosMachine bizPosMachine2) {
        String url= "http://www.poshb.cn:8083/pos/synchronization/lmhb/sameToQuote";
        Map<String, String> data = new HashMap<String, String>();
        data.put("var1", bizPosMachine2.getVar1());
        data.put("posCode", bizPosMachine2.getPosCode());
        data.put("posName", bizPosMachine2.getPosName());
        data.put("posType", bizPosMachine2.getPosType());
        data.put("posActivateStatus", bizPosMachine2.getPosActivateStatus());
        data.put("terminalNo", bizPosMachine2.getTerminalNo());
        data.put("merchId", String.valueOf(bizPosMachine2.getMerchId())); //得写死 许陆
        data.put("manufacturersId", bizPosMachine2.getManufacturersId());
        data.put("deviceType", bizPosMachine2.getDeviceType());
        data.put("modelId", bizPosMachine2.getModelId());
        data.put("simAmt", bizPosMachine2.getSimAmt());
        data.put("simDaynum", bizPosMachine2.getSimDaynum());
        data.put("simIccid", bizPosMachine2.getSimIccid());
        data.put("devImei", bizPosMachine2.getDevImei());
        String result = doPost(url, new Gson().toJson(data));
        JSONObject jsonObject = JSONObject.parseObject(result);
        String ret_code = jsonObject.getString("ret_code");
        return  ret_code;
    }
    /*获取商户编号，插入到设备表*/
    @PostMapping("/set/terminalNo")
    public AjaxResult setTerminalNo() {
        List<BizPosMachine> bizPosMachines= iBizPosMachineService.selectBizPosMachinesSn();
        BizPosMachine bizPosMachine11=new BizPosMachine();
        int rowsSsccous=0;
        int rowsError=0;
        for (BizPosMachine bizPosMachine:bizPosMachines){
            PosTheMdisPlayDTO posTheMdisPlayDTO=new PosTheMdisPlayDTO();
            posTheMdisPlayDTO.setSn(bizPosMachine.getPosCode());
            try {
                PosThemDisPlayedDTO posThemDisPlayedDTO=themdisplayedList(posTheMdisPlayDTO);
                List<PosThemDisPlayedReturnDTO> posThemDisPlayedReturnDTOS =posThemDisPlayedDTO.getPosThemDisPlayedReturnDTOS();

                bizPosMachine11.setTerminalNo(posThemDisPlayedReturnDTOS.get(0).getTerminalNo());
                bizPosMachine11.setPosCode(bizPosMachine.getPosCode());
            } catch (Exception e) {
                e.printStackTrace();
            }
            int row=iBizPosMachineService.updateBizPosMachinesTerminalNo(bizPosMachine11);
            if (row>0){
                rowsSsccous++;
            }else {
                rowsError++;
            }
        }
        return AjaxResult.success("成功=====："+rowsSsccous+"-----失败=====："+rowsError);
    }
    /**
     * post请求
     * @param url
     * @param data
     * @return
     */
    public String doPost(String url,String data){
        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try{
            //创建http请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            //创建请求内容
            String jsonStr = data;
            StringEntity entity = new StringEntity(jsonStr,"utf-8");
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(),"utf-8");
            System.out.println(result);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭资源
            if(response != null){
                try {
                    response.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
            if(httpClient != null){
                try{
                    httpClient.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }
    @PostMapping("/info_login")
    public AjaxResult infoLogin(@RequestBody LoginBody loginBody){
        if(null==loginBody.getCode()||loginBody.getCode().equals("")||loginBody.getCode().equals("null")){
            return AjaxResult.error("请输入身份证后六位");
        }
        if(loginBody.getCode().length()<6){
            return AjaxResult.error("请输入身份证后六位");
        }
        List<BizPosMachineStatusRecords> bizPosMachineStatusRecordsList=posMachineMapper.getRecordsByPhone(loginBody.getCode());
        if(bizPosMachineStatusRecordsList==null||bizPosMachineStatusRecordsList.size()==0){
            return AjaxResult.error("该商户不存在请核实后重试！");
        }
        List<Map<String,String>> list=new ArrayList<Map<String,String>>();
        for (BizPosMachineStatusRecords bizPosMachineStatusRecords:bizPosMachineStatusRecordsList){
            Map<String,String> relMap=new HashMap<String,String>();
            relMap.put("merchantId",bizPosMachineStatusRecords.getMerchantId());
            relMap.put("activeTime",bizPosMachineStatusRecords.getActiveTime());
            relMap.put("snCode",bizPosMachineStatusRecords.getSnCode());
            relMap.put("phoneNo",bizPosMachineStatusRecords.getPhoneNo());
            relMap.put("name",bizPosMachineStatusRecords.getName());
            relMap.put("secretId","AKIDvnxzoQIz8FAe2BfJHHRFo8Fn45rMAdQz");
            relMap.put("secretKey","UouqnWDf2A1cyKn46tQm00whEYvDJI2Z");
            relMap.put("bucketName","cykj-1303987307");
            String bankCardno="";
            if(StringUtils.isBlank(bizPosMachineStatusRecords.getBankCardno())){
                bankCardno=posMachineMapper.selectBankCardnoByEntry(bizPosMachineStatusRecords.getSnCode());
                if(StringUtils.isBlank(bankCardno)){
                    BizMerchantInfo info=posMachineMapper.selectBankCardnoByInfo(bizPosMachineStatusRecords.getSnCode());
                    if(null!=info){
                        bankCardno=info.getBankCardAccount();
                        relMap.put("khbUserId",info.getKhbUserId());
                        relMap.put("khbGroupId",info.getKhbGroupId());
                        relMap.put("khbAccessToken",info.getKhbAccessToken());
                    }
                }
            }else{
                //存在银行卡
                bankCardno=bizPosMachineStatusRecords.getBankCardno();
            }
            relMap.put("bankCardno",bankCardno);
            list.add(relMap);
        }
        return AjaxResult.success(list);
    }
}
